import { defineStore } from 'pinia'
import type { User, AuthResponse } from '~/types'

/**
 * 认证 Store
 */
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoggedIn = computed(() => !!token.value && !!user.value)

  /**
   * 初始化（从本地存储恢复登录状态）
   */
  const init = () => {
    if (process.client) {
      const savedToken = localStorage.getItem('token')
      const savedUser = localStorage.getItem('user')
      
      if (savedToken && savedUser) {
        token.value = savedToken
        user.value = JSON.parse(savedUser)
      }
    }
  }

  /**
   * 登录
   */
  const login = async (email: string, password: string) => {
    const { $api } = useNuxtApp()
    
    try {
      const response = await $api('/auth/login', {
        method: 'POST',
        body: { email, password },
      }) as AuthResponse
      
      token.value = response.token
      user.value = response.user
      
      // 保存到本地存储
      if (process.client) {
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
      }
      
      return { success: true }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.data?.message || '登录失败' 
      }
    }
  }

  /**
   * 注册
   */
  const register = async (email: string, password: string, nickname?: string) => {
    const { $api } = useNuxtApp()
    
    try {
      const response = await $api('/auth/register', {
        method: 'POST',
        body: { email, password, nickname },
      }) as AuthResponse
      
      token.value = response.token
      user.value = response.user
      
      // 保存到本地存储
      if (process.client) {
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
      }
      
      return { success: true }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.data?.message || '注册失败' 
      }
    }
  }

  /**
   * 设置 Token
   */
  const setToken = (newToken: string) => {
    token.value = newToken
    
    if (process.client) {
      localStorage.setItem('token', newToken)
    }
  }

  /**
   * 设置用户信息
   */
  const setUser = (newUser: User) => {
    user.value = newUser
    
    if (process.client) {
      localStorage.setItem('user', JSON.stringify(newUser))
    }
  }

  /**
   * 退出登录
   */
  const logout = () => {
    user.value = null
    token.value = null
    
    if (process.client) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  }

  /**
   * 获取用户信息
   */
  const fetchUser = async () => {
    if (!token.value) return
    
    const { $api } = useNuxtApp()
    
    try {
      const response = await $api('/auth/profile') as User
      user.value = response
      
      if (process.client) {
        localStorage.setItem('user', JSON.stringify(response))
      }
    } catch (error) {
      // Token 无效，清除登录状态
      logout()
    }
  }

  /**
   * 更新用户信息
   */
  const updateUser = async (data: Partial<User>) => {
    const { $api } = useNuxtApp()
    
    try {
      const response:any = await $api('/users/profile', {
        method: 'PATCH',
        body: data,
      })
      
      user.value = response
      
      if (process.client) {
        localStorage.setItem('user', JSON.stringify(response))
      }
      
      return { success: true }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.data?.message || '更新失败' 
      }
    }
  }

  /**
   * 检查是否是会员
   */
  const isPremium = computed(() => {
    if (!user.value) return false
    if (user.value.subscriptionType === 'free') return false
    if (!user.value.subscriptionEndDate) return false
    return new Date() < new Date(user.value.subscriptionEndDate)
  })

  return {
    user,
    token,
    isLoggedIn,
    isAuthenticated: isLoggedIn, // 添加别名以兼容
    isPremium,
    init,
    login,
    register,
    logout,
    setToken,
    setUser,
    fetchUser,
    updateUser,
  }
})


